#include <iostream>
#include <memory>
#include <string>
#include <unistd.h>
#include <fstream>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

std::string SuffixToType(const std::string &suffix)
{
    if (suffix == ".html" || suffix == ".html")
        return "text/html";
    else if (suffix == ".png")
        return "image/png";
    else if (suffix == ".jpg")
        return "image/jpeg";
    else
    {
        return "text/html";
    }
}

std::string CodetoDesc(int code)
{
    switch (code)
    {
    case 200:
        return "OK";
    case 301:
        return "Moved Permanently";
    case 307:
        return "Temporary Redirect";//临时重定向
    case 403:
        return "Forbidden";
    case 404:
        return "Not Found";
    case 500:
        return "Internal Server Error";
    default:
        return "Unknown";
    }
}






std::string HandlerHttpRequest(std::string &request)
{

    HttpRequest req;
    req.Deserialize(request);
    req.Parse();
    req.DebugHttp();
    int code = 200;


    std::string content = req.GetFileContent();
    if (content.empty())
    {
        code = 404;
        content = req.Get_404();
    }

   // code = 307;


    //响应
    HttpResponse resp;
    resp.SetCode(code);
    resp.SetDesc(CodetoDesc(code));
    resp.MakeStatusLine();
    std::string content_len_str = "Content-Length: " + std::to_string(content.size()) + "\r\n";
    resp.AddHeader(content_len_str);
    std::string content_type_str = "Content-Type: " + SuffixToType(req.Suffix()) + "\r\n"; // 正文的类型
    resp.AddHeader(content_type_str);
  
    std::string namecookie = "Set-Cookie: username=kaice\r\n";
    resp.AddHeader(namecookie);
    std::string passwddcookie = "Set-Cookie: password=12345\r\n";
    resp.AddHeader(passwddcookie);
    std::string statuscookie = "Set-Cookie: status=loglined";
    resp.AddHeader(statuscookie);

    resp.AddContent(content);
    
    return resp.Serialize();


//    std::cout << "content: " << content << std::endl;
//     std::cout << "suffix: " << req.Suffix() << "Type: " << SuffixToType(req.Suffix()) << std::endl;
//     if (!content.empty())
//     {
//         std::cout << request << std::endl;

//         std::string httpstatusline = "Http/1.0 200 OK\r\n";
//         std::string httpheader = "Content-Length: " + std::to_string(content.size()) + "\r\n";
//         httpheader += "Content-Type: ";//正文的类型
//         httpheader += "\r\n";

//         std::string httpresponse = httpstatusline + httpheader + content;
//         return httpresponse;
//     }

    
}


// ./server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cout << "Usage : " << argv[0] << " port" << std::endl;
        return 0;
    }
    uint16_t localport = std::stoi(argv[1]);

    std::unique_ptr<TcpServer> svr(new TcpServer(localport, HandlerHttpRequest));

    svr->Loop();

    return 0;
}